/**
 * Mock API 数据层
 * 使用 setTimeout 模拟异步请求
 */

import type { User, UserForm, UserQuery, LoginForm, LoginResponse, ApiResponse, ListResponse } from '@/types'
import { formatDateTime } from '@/utils/format'

/**
 * 模拟初始用户数据
 */
let mockUserData: User[] = [
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    password: '123456',
    role: 'admin',
    status: 'active',
    phone: '13800138000',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-15 14:30:00',
  },
  {
    id: 2,
    username: 'user01',
    email: 'user01@example.com',
    password: '123456',
    role: 'user',
    status: 'active',
    phone: '13800138001',
    createTime: '2024-01-05 09:20:00',
  },
  {
    id: 3,
    username: 'user02',
    email: 'user02@example.com',
    password: '123456',
    role: 'user',
    status: 'inactive',
    phone: '13800138002',
    createTime: '2024-01-10 16:45:00',
  },
  {
    id: 4,
    username: 'testuser',
    email: 'test@example.com',
    password: '123456',
    role: 'user',
    status: 'active',
    phone: '13800138003',
    createTime: '2024-01-12 11:30:00',
  },
  {
    id: 5,
    username: 'manager',
    email: 'manager@example.com',
    password: '123456',
    role: 'admin',
    status: 'active',
    phone: '13800138004',
    createTime: '2024-01-15 08:15:00',
  },
]

/**
 * 生成唯一 ID
 */
let currentId = mockUserData.length + 1
function generateId(): number {
  return currentId++
}

/**
 * 模拟网络延迟
 */
function mockRequest<T>(data: T, delay: number = 500): Promise<T> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(data)
    }, delay)
  })
}

/**
 * 模拟登录
 */
export async function mockLogin(form: LoginForm): Promise<ApiResponse<LoginResponse>> {
  const user = mockUserData.find(
    (u) => u.username === form.username && u.password === form.password
  )

  if (!user) {
    return mockRequest<ApiResponse<LoginResponse>>({
      success: false,
      data: null as any,
      message: '用户名或密码错误',
    }, 800)
  }

  if (user.status === 'inactive') {
    return mockRequest<ApiResponse<LoginResponse>>({
      success: false,
      data: null as any,
      message: '账号已被禁用',
    }, 800)
  }

  // 移除密码字段
  const { password, ...userInfo } = user

  return mockRequest<ApiResponse<LoginResponse>>({
    success: true,
    data: {
      token: `mock_token_${user.id}_${Date.now()}`,
      user: userInfo,
    },
    message: '登录成功',
  }, 800)
}

/**
 * 获取用户列表
 */
export async function mockGetUserList(
  query: UserQuery
): Promise<ApiResponse<ListResponse<User>>> {
  const {
    page = 1,
    pageSize = 10,
    keyword = '',
    role,
    status,
    sortField,
    sortOrder,
  } = query

  // 过滤数据
  let filteredData = mockUserData.filter((user) => {
    // 关键词搜索（用户名或邮箱）
    if (keyword) {
      const lowerKeyword = keyword.toLowerCase()
      const matchKeyword =
        user.username.toLowerCase().includes(lowerKeyword) ||
        user.email.toLowerCase().includes(lowerKeyword)
      if (!matchKeyword) return false
    }

    // 角色过滤
    if (role && user.role !== role) return false

    // 状态过滤
    if (status && user.status !== status) return false

    return true
  })

  // 排序
  if (sortField && sortOrder) {
    filteredData.sort((a, b) => {
      const aValue = a[sortField as keyof User]
      const bValue = b[sortField as keyof User]

      if (typeof aValue === 'string' && typeof bValue === 'string') {
        return sortOrder === 'ascend'
          ? aValue.localeCompare(bValue)
          : bValue.localeCompare(aValue)
      }

      if (typeof aValue === 'number' && typeof bValue === 'number') {
        return sortOrder === 'ascend' ? aValue - bValue : bValue - aValue
      }

      return 0
    })
  }

  const total = filteredData.length

  // 分页
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredData.slice(start, end).map((user) => {
    // 移除密码字段
    const { password, ...userWithoutPassword } = user
    return userWithoutPassword as User
  })

  return mockRequest<ApiResponse<ListResponse<User>>>({
    success: true,
    data: {
      list,
      total,
    },
    message: '获取成功',
  }, 600)
}

/**
 * 添加用户
 */
export async function mockAddUser(form: UserForm): Promise<ApiResponse<User>> {
  // 检查用户名是否已存在
  const existingUser = mockUserData.find((u) => u.username === form.username)
  if (existingUser) {
    return mockRequest<ApiResponse<User>>({
      success: false,
      data: null as any,
      message: '用户名已存在',
    }, 500)
  }

  // 检查邮箱是否已存在
  const existingEmail = mockUserData.find((u) => u.email === form.email)
  if (existingEmail) {
    return mockRequest<ApiResponse<User>>({
      success: false,
      data: null as any,
      message: '邮箱已被使用',
    }, 500)
  }

  const newUser: User = {
    id: generateId(),
    username: form.username,
    email: form.email,
    password: form.password || '123456',
    role: form.role,
    status: form.status,
    phone: form.phone,
    createTime: formatDateTime(new Date()),
  }

  mockUserData.push(newUser)

  // 移除密码字段
  const { password, ...userWithoutPassword } = newUser

  return mockRequest<ApiResponse<User>>({
    success: true,
    data: userWithoutPassword as User,
    message: '添加成功',
  }, 700)
}

/**
 * 更新用户
 */
export async function mockUpdateUser(
  id: number,
  form: UserForm
): Promise<ApiResponse<User>> {
  const userIndex = mockUserData.findIndex((u) => u.id === id)

  if (userIndex === -1) {
    return mockRequest<ApiResponse<User>>({
      success: false,
      data: null as any,
      message: '用户不存在',
    }, 500)
  }

  // 检查用户名是否被其他用户使用
  const existingUser = mockUserData.find(
    (u) => u.username === form.username && u.id !== id
  )
  if (existingUser) {
    return mockRequest<ApiResponse<User>>({
      success: false,
      data: null as any,
      message: '用户名已存在',
    }, 500)
  }

  // 检查邮箱是否被其他用户使用
  const existingEmail = mockUserData.find(
    (u) => u.email === form.email && u.id !== id
  )
  if (existingEmail) {
    return mockRequest<ApiResponse<User>>({
      success: false,
      data: null as any,
      message: '邮箱已被使用',
    }, 500)
  }

  const updatedUser: User = {
    ...mockUserData[userIndex],
    username: form.username,
    email: form.email,
    role: form.role,
    status: form.status,
    phone: form.phone,
    updateTime: formatDateTime(new Date()),
  }

  // 如果提供了新密码，则更新密码
  if (form.password) {
    updatedUser.password = form.password
  }

  mockUserData[userIndex] = updatedUser

  // 移除密码字段
  const { password, ...userWithoutPassword } = updatedUser

  return mockRequest<ApiResponse<User>>({
    success: true,
    data: userWithoutPassword as User,
    message: '更新成功',
  }, 700)
}

/**
 * 删除用户
 */
export async function mockDeleteUser(id: number): Promise<ApiResponse<null>> {
  const userIndex = mockUserData.findIndex((u) => u.id === id)

  if (userIndex === -1) {
    return mockRequest<ApiResponse<null>>({
      success: false,
      data: null,
      message: '用户不存在',
    }, 500)
  }

  // 不允许删除 admin 用户
  if (mockUserData[userIndex].username === 'admin') {
    return mockRequest<ApiResponse<null>>({
      success: false,
      data: null,
      message: '不能删除管理员账户',
    }, 500)
  }

  mockUserData.splice(userIndex, 1)

  return mockRequest<ApiResponse<null>>({
    success: true,
    data: null,
    message: '删除成功',
  }, 600)
}

/**
 * 批量删除用户
 */
export async function mockBatchDeleteUser(ids: number[]): Promise<ApiResponse<null>> {
  // 检查是否包含 admin 用户
  const hasAdmin = mockUserData.some(
    (u) => ids.includes(u.id) && u.username === 'admin'
  )

  if (hasAdmin) {
    return mockRequest<ApiResponse<null>>({
      success: false,
      data: null,
      message: '不能删除管理员账户',
    }, 500)
  }

  mockUserData = mockUserData.filter((u) => !ids.includes(u.id))

  return mockRequest<ApiResponse<null>>({
    success: true,
    data: null,
    message: `成功删除 ${ids.length} 个用户`,
  }, 700)
}

/**
 * 获取用户详情
 */
export async function mockGetUserDetail(id: number): Promise<ApiResponse<User>> {
  const user = mockUserData.find((u) => u.id === id)

  if (!user) {
    return mockRequest<ApiResponse<User>>({
      success: false,
      data: null as any,
      message: '用户不存在',
    }, 500)
  }

  // 移除密码字段
  const { password, ...userWithoutPassword } = user

  return mockRequest<ApiResponse<User>>({
    success: true,
    data: userWithoutPassword as User,
    message: '获取成功',
  }, 500)
}
